import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Form,
  Input,
  Button,
  Divider,
  message,
  Tabs,
  Space,
  Typography,
  Alert,
  Popconfirm,
} from 'antd';
import {
  UserOutlined,
  SecurityScanOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  DeleteOutlined,
  SaveOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import { getCurrentUser, updateUserProfile, changePassword, regeneratePasskey } from '../api/user';
import { User } from '../types';

const { Title, Text } = Typography;

interface SettingsForm {
  email: string;
  signature: string;
}

interface PasswordForm {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const Settings: React.FC = () => {
  const { user: authUser } = useAuth();
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('profile');
  
  // 表单实例
  const [profileForm] = Form.useForm<SettingsForm>();
  const [passwordForm] = Form.useForm<PasswordForm>();

  useEffect(() => {
    fetchUserData();
  }, []);

  const fetchUserData = async () => {
    try {
      setLoading(true);
      
      const userResponse = await getCurrentUser();
      
      if (userResponse.code === 200) {
        setUser(userResponse.data);
        
        // 初始化表单数据
        profileForm.setFieldsValue({
          email: userResponse.data.email,
          signature: userResponse.data.signature || '',
        });
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      message.error('获取用户信息失败');
    } finally {
      setLoading(false);
    }
  };

  const handleProfileUpdate = async (values: SettingsForm) => {
    try {
      setLoading(true);
      const response = await updateUserProfile({
        email: values.email,
        bio: values.signature,
      });
      
      if (response.code === 200) {
        setUser(response.data);
        message.success('个人信息更新成功');
      } else {
        message.error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('更新失败:', error);
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordChange = async (values: PasswordForm) => {
    try {
      setLoading(true);
      const response = await changePassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
      });
      
      if (response.code === 200) {
        message.success('密码修改成功');
        passwordForm.resetFields();
      } else {
        message.error(response.message || '修改失败');
      }
    } catch (error) {
      console.error('修改密码失败:', error);
      message.error('修改密码失败');
    } finally {
      setLoading(false);
    }
  };

  const handleRegeneratePasskey = async () => {
    try {
      setLoading(true);
      const response = await regeneratePasskey();
      if (response.code === 200) {
        message.success('Passkey重新生成成功');
        fetchUserData(); // 重新获取用户信息
      } else {
        message.error(response.message || '重新生成失败');
      }
    } catch (error) {
      console.error('重新生成Passkey失败:', error);
      message.error('重新生成失败');
    } finally {
      setLoading(false);
    }
  };

  const profileTab = (
    <Card>
      <Title level={4}>
        <UserOutlined /> 个人信息设置
      </Title>
      <Form
        form={profileForm}
        layout="vertical"
        onFinish={handleProfileUpdate}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="邮箱地址"
              name="email"
              rules={[
                { required: true, message: '请输入邮箱地址' },
                { type: 'email', message: '邮箱格式不正确' },
              ]}
            >
              <Input placeholder="请输入邮箱地址" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="用户名">
              <Input value={user?.username} disabled />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="个性签名"
          name="signature"
          rules={[
            { max: 200, message: '个性签名不能超过200个字符' },
          ]}
        >
          <Input.TextArea 
            rows={4} 
            placeholder="介绍一下自己..." 
            showCount
            maxLength={200}
          />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
            >
              保存更改
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );

  const securityTab = (
    <Card>
      <Title level={4}>
        <SecurityScanOutlined /> 账户安全
      </Title>
      
      {/* 修改密码 */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Title level={5}>修改密码</Title>
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordChange}
        >
          <Form.Item
            label="当前密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password
              placeholder="请输入当前密码"
              iconRender={visible => visible ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password
              placeholder="请输入新密码"
              iconRender={visible => visible ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            />
          </Form.Item>

          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password
              placeholder="请再次输入新密码"
              iconRender={visible => visible ? <EyeOutlined /> : <EyeInvisibleOutlined />}
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
            >
              修改密码
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {/* Passkey管理 */}
      <Card size="small">
        <Title level={5}>Passkey管理</Title>
        <Alert
          message="重要提示"
          description="Passkey用于客户端连接，重新生成后需要在所有BT客户端中更新。"
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
        
        <Space direction="vertical" style={{ width: '100%' }}>
          <div>
            <Text strong>当前Passkey: </Text>
            <Text code copyable>{user?.passkey}</Text>
          </div>
          <Popconfirm
            title="确定要重新生成Passkey吗？"
            description="重新生成后，所有正在使用的客户端都需要更新Passkey。"
            onConfirm={handleRegeneratePasskey}
            okText="确定"
            cancelText="取消"
          >
            <Button danger icon={<DeleteOutlined />}>
              重新生成Passkey
            </Button>
          </Popconfirm>
        </Space>
      </Card>
    </Card>
  );

  const tabItems = [
    {
      key: 'profile',
      label: '个人信息',
      children: profileTab,
      icon: <UserOutlined />,
    },
    {
      key: 'security',
      label: '账户安全',
      children: securityTab,
      icon: <SecurityScanOutlined />,
    },
  ];

  return (
    <div>
      <Title level={2}>
        <SettingOutlined /> 设置
      </Title>
      
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="large"
      />
    </div>
  );
};

export default Settings; 